package com.easy.common.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.easy.common.util.BeanUtil;

public class FilterUtil {

	/**
	 * 将json数组转换为domain对象
	 * 
	 * @param clazz
	 *            domain对象类型
	 * @param filterRule
	 *            json字符串
	 * @return domain对象
	 */
	@SuppressWarnings("rawtypes")
	public static Object getVO(Class clazz, String filterRule) {

		Object t = null;
		try {
			if (filterRule != null) {
				t = clazz.newInstance();
				List<FilterRule> list = getFilterList(filterRule);

				if (list != null) {
					for (FilterRule filerRule : list) {
						String field = filerRule.getField();
						String value = filerRule.getValue();
						BeanUtil.invokeSet(t, field, value);
					}
				}
			} else {
				t = clazz.newInstance();
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		return t;
	}

	/**
	 * 将json字符串转会为过滤参数FilterRule类的数组
	 * 
	 * @param filterRule
	 *            json字符串
	 * @return FilterRule的对象数组
	 */
	@SuppressWarnings("rawtypes")
	public static List<FilterRule> getFilterList(String filterRule) {

		JSONArray filterRuleArray = JSONArray.fromObject(filterRule);

		Collection filterRuleCollection = JSONArray
				.toCollection(filterRuleArray);

		List<FilterRule> result = new ArrayList<FilterRule>();

		if (filterRuleCollection != null && !filterRuleCollection.isEmpty()) {
			Iterator it = filterRuleCollection.iterator();
			while (it.hasNext()) {
				JSONObject ruleJSONObj = JSONObject.fromObject(it.next());
				FilterRule rule = (FilterRule) JSONObject.toBean(ruleJSONObj,
						FilterRule.class);
				result.add(rule);
			}
		}

		return result;
	}
}
